import * as CryptoJS from 'crypto-js';
import { SM4 } from 'gm-crypto';

/**
 * 密码加密
 * @param {Object} word
 * @author 瑾年
 * @return str
 */
export function encrypt(word) {
    var key = CryptoJS.enc.Utf8.parse("AESmoss077o3WERT");
    var srcs = CryptoJS.enc.Utf8.parse(word);
    var encrypted = CryptoJS.AES.encrypt(srcs, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 });
    return encrypted.toString();
}
/**
 * 解密
 * @param word
 * @author 瑾年
 * @return str
 */
export function decrypt(word) {
    var key = CryptoJS.enc.Utf8.parse("AESmoss077o3WERT");
    var decrypt = CryptoJS.AES.decrypt(word, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 });
    return CryptoJS.enc.Utf8.stringify(decrypt).toString();
}

/**
 * SM4加密解密key需要转为32位16进制数
 * @param {*} str 
 * @returns 
 */
export function stringToHex(str){
    let val = ''
    for (let i = 0; i < str.length; i++) {
    val += str.charCodeAt(i).toString(16)
    }
    return val
}
/**
 * 加密
 * @param {Object} word
 * @author 瑾年
 * @return str
 */
export	function SM4encrypt(key,word) {
    const encrypt = SM4.encrypt(word, stringToHex(key), {
    inputEncoding: 'utf8',
    outputEncoding: 'hex'
    });
    return encrypt.toLowerCase();
}
/**
 * 解密
 * @param word
 * @author 瑾年
 * @return str
 */
export	function SM4decrypt(key,word) {
    const decrypt = SM4.decrypt(word, stringToHex(key), {
    inputEncoding: 'utf8',
    outputEncoding: 'hex'
    });
    return decrypt;
}

